define(['config', 'text!app/module/system/addTranslate.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/translate";
    
    var grid_arr = new Array();
    
    var item = 0;
    
    var deliveryNoteNo = Public.getRequestParam ("deliveryNoteNo");;
    
    function r(val, opt, row) {
    	
		 
		 var html_con = '<div class="operating" data-id="' + row.id + '"><input id="i'+ row.id + '" class = "stowage" style = "width: 100%" /></div>';
   	 
		 return html_con;
    }
    
    var model = avalon.define({
    	$id : "addTranslate",
         // 查询条件 	
         query: {
        	 orderNo: "",
         },
         deliveryInfo:{
        	id:"",
       		uuid:"",
       		deliveryNoteNo:"",//送货单号
       		consignee:"",//收货人
       		modeOfShipment:"",//装运方式
       		shippingTerms:"",		//装运条款
       		mailingAddress:"",//邮寄地址
       		deliverDate:"",//发货日期
       		carrier:"",//承运人
       		carrierPhone:"",//成员人电话
       		status:"0"//状态
         },
         deliverydetailInfo :{
        	id:"",
          	uuid:"",
          	deliveryNoteNo:"",//送货单号
          	orderNo:"",//订单号
          	lotNo:"",//批次号
          	name:"",//品名
          	model:"",//规格
          	color:"",//颜色
      		amount:"",//总数
      		orderDetailUuid:""
          },
          isEmpty: function (value, alerttxt) {
	          if (value == null || value == "") {
	              Public.tips({
	                      type: 2,
	                      content: alerttxt
	                  });
	               return false;
           }else {
	              return true;
	       }
	     },
         statusArr: [],
         selected: [],
         roles: [],
         
         init: function () {
        	 model.initPage();
             model.addEvent();
         },
         initPage:function(){
        	 function t(val, opt, row) {
	            	
        		 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
            	 
        		 return html_con;
             }
	 	        console.log('[arr2.deliveryNoteNo]',deliveryNoteNo);
		        	 $.ajax({
		                 type: "POST",
		                 url: "/api/translate/findByDeliveryNoteNo",
		                 data: {
		                	 "page":1,
		                	 "rows":1,
		                     "deliveryNoteNo": deliveryNoteNo
		                 },
		                 beforeSend: function (xhr) {
		                     xhr.setRequestHeader("X-AuthToken", token);
		                 },
		                 success: function (data) {
		                	 
		                	 
		                	 if(data){
		                		 console.log('[data3]',data);
		                		 model.deliveryInfo = data;
		                		 console.log('[model.deliveryInfo]',model.deliveryInfo);
		                		 console.log('[model.deliveryInfo.status]',model.deliveryInfo.status);
		                		 if(model.deliveryInfo.status == 1){
		                			 $("#detailInfo input").attr("readOnly","true");
		                		 }
		                	 }else{
		                		 $.ajax({
		                			 type:"POST",
		                             url: "/api/translate/getDeliveryNoteNo",
		                             success:function(data){
		                            	 console.log('[data1]',data);
		                            	 model.initdelivery();
		                            	 model.deliveryInfo.deliveryNoteNo=data;
		                            	 console.log('[data2]',model.deliveryInfo.deliveryNoteNo);
		                             },

		                             beforeSend: function (xhr) {
		                                 xhr.setRequestHeader("X-AuthToken", token);
		                             },
		                             error: function (responseData, textStatus, errorThrown) {
		                                 alert("Failed: " + responseData);
		                             }
		                		 });
		                	 }
		                	 
		                 },
		             error: function (responseData, textStatus, errorThrown) {
		                 alert("Failed: " + responseData);
		             }
		        	 });
		        	 $.ajax({
	        			 type:"POST",
	                     url: "/api/translate/getdetail",
	                     data: {
	                         "deliveryNoteNo":deliveryNoteNo
	                     },
	                     success:function(data){
	                    	 console.log('[data1111111]',data);
	                    	 grid_arr = data;
	                    	 console.log('[grid_arr]',grid_arr);
	                    	 model.reLoadGrid();
	                     },

	                     beforeSend: function (xhr) {
	                         xhr.setRequestHeader("X-AuthToken", token);
	                     },
	                     error: function (responseData, textStatus, errorThrown) {
	                         alert("Failed: " + responseData);
	                     }
	        		 });
	            	 $("#grid").jqGrid({
            		     datatype: "local",
            		     data:grid_arr,
                         colModel: [{
                             name: "operating",
                             label: "操作",
                             width: '5%',
                             formatter: t,
                         },
                         {
                             name: "orderNo",
                             label:"订单号",
                             width: '10%',
                         },
                         {
                             name: "name",
                             label: "品名",
                             width: '8%',
                         },
                         {
                             name: "model",
                             label: "规格",
                             width: '10%',
                         },
                         {
                             name: "amount",
                             label: "总件",
                             width: '13%',
                         },
                         {
   		                	  name:"pn",
   		                	  label:"物料号",
   		                	  width:'10%',
   		                	  hidden:true
   		                  },
   		                  {
   		                	  name:"sku",
   		                	  label:"sku",
   		                	  width:'10%',
   		                  },
   		                  {
		                      name: "stowageNo",
		                      label: "配载数量",
		                      width: '7%',
		                  }
                           ],
                           page: 1,
                           rowNum: 10,
                           rowList: [10, 20, 30],
                           height: '250px',
                           autowidth: true,
                           pager: '#page',
                           sortname: 'id',
                           viewrecords: true,
                           forceFit: false,
                           rownumbers: true,
                           multiselect: true,
                           multiboxonly: true,
                           sortorder: "desc",
            		 });
	            	 
	         },
         reLoadGrid: function () {
             $("#grid").jqGrid("setGridParam", {
            	 datatype: "local",
    		     data:grid_arr,
                 page:1,
             }).trigger("reloadGrid");
         },
         /**删除商品*/
         del: function (id) {
        	 console.log('[id]',id);
             dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {
                     for (var i = 0; i < grid_arr.length; i++) {
						if(grid_arr[i].id == id){
							grid_arr.splice(i,1);
							$('#grid').jqGrid('delRowData', id);
							console.log('[grid_arr]',grid_arr);
						}
						model.reLoadGrid();
					}
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
             
             
         },
         add:function(){
        	 var rowData;
        	 
        	 $(".grid-wrap").on("click", function (e) {
        		 var selectedId = $("#grid_d").jqGrid("getGridParam","selrow"); 
            	 console.log('[selectedId]',selectedId);
	        	 rowData =  $("#grid_d").getRowData(selectedId);
	        	 console.log('[rowData]',rowData);
        	 });
        	 dialog({
                 title: '配载',
                 content: $('#editUser'),
                 okValue: "确定",
                 ok: function () {
                	 console.log('rowData',rowData);
                	 var t = $("#grid_d").jqGrid("getGridParam", "selarrrow");
                	 console.log('t',t);
                	 for (var i = 0; i < t.length; i++) {
                		console.log('[$("#grid").getRowData(t[i])]',$("#grid").getRowData(t[i]));
                		var data = $("#grid_d").getRowData(t[i]);
                	    var id = "i"+t[i];
                		data.stowageNo =document.getElementById(id).value;
                		if(parseInt(data.already) - parseInt(data.stowageNo) < 0){
                			dialog({
                                title: "错误",
                                content: "成品数量不足！",
                                okValue: "确定",
               	        	   ok: function (){
               	        	 }
                       	 }).showModal();
                   		 return;
                		}
                		data.id=new Date().getTime();
                		grid_arr.push(data);
						console.log('[grid_arr]',grid_arr); 
					 }
                	 model.reLoadGrid();
                 },
	             cancelValue: "取消",
                 cancel: function () {
                 }
             }).showModal();
         },
         addEvent: function () {
             var t = this;
        	 //返回
             $(".fr").on("click", "#close", function (e){
            	 console.log('1111111111111111111111');
                 top.topManager.closePage();
                 top.topManager.openPage({
          			id:"translateManage",
          			title:"运输管理",
          			href:'index.html#!/115',
          			reload:true
          		 })
             });
             //添加商品
             $(".grid-wrap").on("click", "#addGoods", function (e) {
            	 
                 $("#grid_d").jqGrid({
                	 loadBeforeSend: function (jqXHR) {
                         jqXHR.setRequestHeader("X-AuthToken", token);
                     },
                     datatype: "json",
                     url:"api/produce/getStowageList",
                     mtype: 'POST',
                     cache:false,
                     postData: {},
    	             loadComplete:function (data) {
                    	 console.log("[data111111111122222222222222]",data.data);
                     },
                     loadError: function (xhr, status, error) {
                         alert(JSON.parse(xhr.responseText).msg);
                     },
   		             colModel: [
                          {
		                      name: "orderNo",
		                      label: "订单号",
		                      width: 100,
		                  },
		                  {
		                      label:"客户",
		                      width: 40,
		                      formatter:function(){
		                    	  return "3M"
		                    	  },
		                  },
		                  {
		                	  name:"orderDetailUuid",
		                	  label:"订单明细uuid",
	                		  hidden:true
		                  },
		                  {
		                      name: "amount",
		                      label:"订单数量",
		                      width: 60,
		                  },
		                  {
		                	  name:"name",
		                	  label:"品名",
		                	  width:120,
		                  },
		                  {
		                	  name:"pn",
		                	  label:"料号",
		                	  width:100,
		                	  hidden:true
		                  },
		                  {
		                	  name:"sku",
		                	  label:"sku",
		                	  width:100,
		                  },
		                  {
		                	  name:"model",
		                	  label:"规格",
		                	  width:50,
		                  },
		                  {
		                      name: "already",
		                      label: "成品数量",
		                      width: 60,
		                  },
		                  {
		                      name: "stowageNo",
		                      label: "配载数量",
		                      width: 80,
		                      formatter:r,
		                  },
		                  {
		                	  name:"goodsUuid",
		                	  label:"goodsUuid",
		                	  hidden:true
		                		  
		                  }
		              ],
                     cmTemplate: {
                     sortable: false,
                     title: false
                     },
                     sortname: 'id',
                     viewrecords: true,
                     forceFit: false,
                     rownumbers: true,
                     multiselect: true,
                     multiboxonly: true,
                     sortorder: "desc",
                     autoScroll: false,
                     height: 200,
                     altRows: true,
                     gridview: true,
                     autowidth: true,
                     jsonReader: {
                         root: "data",
                     },
                 });
                 model.add();
             });
            
             //提交表单
             $(".fr").on("click","#save",function(e){
            	 if(model.isEmpty(model.deliveryInfo.deliverDate.trim(),"发货日期不能为空！")){
            		 
            	
            	 if(item === 1){
            		 dialog({
                         title: "错误",
                         content: "请勿重复提交！",
                         okValue: "确定",
        	        	   ok: function (){
        	        	 }
                	 }).showModal();
            		 return;
            	 }
            	 
            	 for (var i = 0; i < grid_arr.length; i++) {
            		 grid_arr[i].id = "";
            		 grid_arr[i].deliveryNoteNo = model.deliveryInfo.$model.deliveryNoteNo;
				}
            	 if(grid_arr.length == 0){
            		 model.deliveryInfo.$model.status = 0;
            	 }else if(grid_arr.length > 0){
            		 model.deliveryInfo.$model.status = 1;
            	 }
            	 
            	 console.log('[model.deliveryInfo]',model.deliveryInfo);
            	 
            	 var map = {
            			 deliveryNoteNo:model.deliveryInfo.$model.deliveryNoteNo,
            			 delivery:model.deliveryInfo.$model,
            			 arr:grid_arr
            	 };
            	 
            	 $.ajax({
            		 contentType: "application/json;charset=utf-8",
            		 type:"POST",
                     url: "/api/translate/save",
                     data:JSON.stringify(map),
                     success:function(data){
                    	 dialog({
	                           title: "保存成功",
	                           content: "保存成功！",
	                           okValue: "确定",
	          	        	   ok: function (){
	          	        		   item = 1;
	          	        	 }
	                  	 }).showModal();
                     },
                     beforeSend: function (xhr) {
                         xhr.setRequestHeader("X-AuthToken", token);
                     },
                     error: function (responseData, textStatus, errorThrown) {
                         dialog({
	                           title: "保存失败",
	                           content: "保存失败！",
	                           okValue: "确定",
	          	        	 ok: function (){
	          	        	 }
	                  	 }).showModal();
                     }
            	 });
        	  }
             });
             //删除
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
            	 
            	 console.log('[model.deliveryInfo.status]',model.deliveryInfo.status);
            	 if(model.deliveryInfo.status == 1){
            		 dialog({
                         title: "删除失败",
                         content: "配载中，请勿删除！",
                         okValue: "确定",
                         ok: function () {
                         },
                         cancelValue: "取消",
                         cancel: function () {}
                     }).showModal();
        			 return ;
        		 }else{
        			 var selectedId = $("#grid").jqGrid("getGridParam","selrow"); 
                	 console.log('[selectedId11111]',selectedId);
                  	   model.del(selectedId);
        		 }
            	 
             });
         },
         initdelivery:function(){
        	 model.deliveryInfo={
             	id:"",
           		uuid:"",
           		deliveryNoteNo:"",//送货单号
           		consignee:"",//收货人
           		modeOfShipment:"",//装运方式
           		shippingTerms:"",		//装运条款
           		mailingAddress:"",//邮寄地址
           		deliverDate:"",//发货日期
           		carrier:"",//承运人
           		carrierPhone:"",//成员人电话
           		status:"0"//状态
             }
         },
         initdeliverydetail: function () {
             model.deliverydetailInfo={
            	id:"",
               	uuid:"",
               	deliveryNoteNo:"",//送货单号
               	orderNo:"",//订单号
               	lotNo:"",//批次号
               	name:"",//品名
               	model:"",//规格
               	color:"",//颜色
           		amount:""//总数
               }
             }
    });
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});